//
//  BKDevQuickLoginUserModel.m
//  BKDevMenu
//
//  Created by luzz on 2021/11/10.
//

#import "BKDevQuickLoginUserModel.h"
#import <Security/Security.h>

#define KEY_QUICKLOGIN_IDENTIFIER @"com.BKDev.www.BKDevMenu"



@interface BKDevKeyChain : NSObject

@end

@implementation BKDevKeyChain

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            service, (id)kSecAttrService,
            service, (id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}

+ (void)save:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}

+ (id)load:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}

+ (void)delete:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}

@end


@implementation BKDevQuickLoginUserModel

-(id)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {
        _title = [[aDecoder decodeObjectForKey:@"title"] copy];
        _userId = [[aDecoder decodeObjectForKey:@"userId"] copy];
        _pwd = [[aDecoder decodeObjectForKey:@"pwd"] copy];
    }
    return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_title forKey:@"title"];
    [aCoder encodeObject:_userId forKey:@"userId"];
    [aCoder encodeObject:_pwd forKey:@"pwd"];
}



+(NSArray <BKDevQuickLoginUserModel *>*)modelArray
{
    NSArray * list = [BKDevKeyChain load:KEY_QUICKLOGIN_IDENTIFIER];

    return [list isKindOfClass:[NSArray class]]?list:[NSArray array];
}
+(BOOL)clearAll
{
    [BKDevKeyChain delete:KEY_QUICKLOGIN_IDENTIFIER];
    return YES;
}

-(BOOL)save
{
    if (!(self.userId.length > 0)) {
        return NO;
    }
    if (!(self.pwd.length > 0)) {
        return NO;
    }
    if (!(self.title.length > 0)) {
        self.title = @"untitle";
    }
    NSMutableArray * arr = [BKDevQuickLoginUserModel modelArray].mutableCopy;
    if (!arr) {
        arr = @[].mutableCopy;
    }
    BOOL contain = NO;
    for (BKDevQuickLoginUserModel * model in arr) {
        if ([model.userId isEqualToString:self.userId]) {
            
            model.title = self.title;
            model.pwd = self.pwd;
            contain = YES;
            break;
        }
    }
    
    if (contain == NO) {
        [arr addObject:self];
    }
    
    
    [BKDevKeyChain save:KEY_QUICKLOGIN_IDENTIFIER data:arr];
    
    return YES;
    
}
-(BOOL)del
{
    if (!(self.userId.length > 0)) {
        return NO;
    }
    if (!(self.pwd.length > 0)) {
        return NO;
    }
    if (!(self.title.length > 0)) {
        self.title = @"untitle";
    }
    NSMutableArray * arr = [BKDevQuickLoginUserModel modelArray].mutableCopy;
    if (!arr) {
        arr = @[].mutableCopy;
    }
    NSInteger targetIndex = -1;
    for (int i = 0;i<arr.count;i++) {
        BKDevQuickLoginUserModel * model = arr[i];
        if ([model.userId isEqualToString:self.userId]) {
            targetIndex = i;
            break;
        }
    }
    if (targetIndex >= 0) {
        [arr removeObjectAtIndex:targetIndex];
        [BKDevKeyChain save:KEY_QUICKLOGIN_IDENTIFIER data:arr];
        
        return YES;
    }else{
        return YES;
    }
    
}
@end
